package it.uniroma2.tesi.bellomaria;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class RunScript {

	// metodo che esegue gli script sql.
	public void executeScript(String mode){
		
		if(RssParser.pathLavoro==null){
			System.out.println("Parametro path obbligatorio");
			System.exit(0);
		}
		
		System.out.println("Inizio Elaborazione......");
		if(mode.equals("create"))
			executeSqlScript(DBConnection.getConnection(), new File(Utility.getScriptPath(mode)+"/scriptCinema.sql"));
			
		executeSqlScript(DBConnection.getConnection(), new File(Utility.getScriptPath(mode)+"/scriptFilm.sql"));
		executeSqlScript(DBConnection.getConnection(), new File(Utility.getScriptPath(mode)+"/scriptPersona.sql"));
		executeSqlScript(DBConnection.getConnection(), new File(Utility.getScriptPath(mode)+"/scriptFilmHasPersona.sql"));
		executeSqlScript(DBConnection.getConnection(), new File(Utility.getScriptPath(mode)+"/scriptSala.sql"));
		executeSqlScript(DBConnection.getConnection(), new File(Utility.getScriptPath(mode)+"/scriptSalaProiettaFilm.sql"));
		System.out.println("Esecuzione Terminata.");
		DBConnection.closeConnection();
	}

	private void executeSqlScript(Connection conn, File inputFile) {

		// delimitatore per suddividere i singoli stmt nel file.sql
		String delimiter = "\\r\\n";

		// creazione dello scanner
		Scanner scanner;
		try {
			scanner = new Scanner(inputFile, "UTF-8").useDelimiter(delimiter);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			return;
		}

		// scorre il file per leggere gli statement sql.
		Statement currentStatement = null;
		while (scanner.hasNext()) {

			// si prende lo statement.
			String rawStatement = scanner.next();
			
			try {
				// si esegue lo statement.
				System.out.println(rawStatement);
				currentStatement = conn.createStatement();
				currentStatement.execute(rawStatement);
			} catch (SQLException e) {
				System.out.println("SQLState : " + e.getSQLState());
				System.out.println("ErrorCode : " + e.getErrorCode());
				System.out.println("Message : " + e.getMessage());
				System.out.println("----------------------------------------");
			} finally {
				// rilascio delle risorse.
				if (currentStatement != null) {
					try {
						currentStatement.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
				}
				currentStatement = null;
			}
		}
	}
}
